/**
 * Project: apollo-soa-springboot
 * 
 * File Created at 2016年5月13日
 * 
 * Copyright 2015-2016 dx.com Croporation Limited.
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of
 * DongXue software Company. ("Confidential Information").  You shall not
 * disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into
 * with dx.com.
 */
package com.dx.soa.boot.core.datasource;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/** 
* @ClassName: DynamicDataSourceAspect 
* @Description: 切换数据源Advice
* @author wuzhenfang(wzfbj2008@163.com)
* @date 2016年5月13日 下午2:40:55 
* @version V1.0 
*/
@Aspect
@Order(-1)// 保证该AOP在@Transactional之前执行
@Component
public class DynamicDataSourceAspect {

	private static final Logger logger = Logger.getLogger(DynamicDataSourceAspect.class);

	@Before("@annotation(ds)")
	public void changeDataSource(JoinPoint point, TargetDataSource ds) throws Throwable {
		String dsId = ds.name();
		if (!DynamicDataSourceContextHolder.containsDataSource(dsId)) {
			StringBuilder stringb = new StringBuilder();
			stringb.append("数据源[{").append(ds.name()).append(" ]不存在，使用默认数据源 >  ").append(point.getSignature()).toString();
			logger.error(stringb);
		} else {
			StringBuilder stringb = new StringBuilder();
			stringb.append("Use DataSource :").append(ds.name()).append(" > ").append(point.getSignature()).toString();
			logger.debug(stringb);
			DynamicDataSourceContextHolder.setDataSourceType(ds.name());
		}
	}

	@After("@annotation(ds)")
	public void restoreDataSource(JoinPoint point, TargetDataSource ds) {
		StringBuilder stringb = new StringBuilder();
		stringb.append("Revert DataSource :").append(ds.name()).append(" > ").append(point.getSignature()).toString();
		logger.debug(stringb);
		DynamicDataSourceContextHolder.clearDataSourceType();
	}

}
